package com.lntea.netty.demo.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.junit.Test;

public class ScatterAndGatherTest {
    
    public Charset charset = Charset.forName("utf-8"); 

    @Test
    public void testScatter() throws IOException, URISyntaxException{
        RandomAccessFile file = new RandomAccessFile(new File(this.getClass().getResource("input.txt").toURI()), "rw");
        FileChannel channel = file.getChannel();
        
        ByteBuffer buf1 = ByteBuffer.allocate(48);
        ByteBuffer buf2 = ByteBuffer.allocate(48);
        
        
        ByteBuffer[] bufArray = {buf1,buf2};
        long read = channel.read(bufArray);
        
        
        while(read!=-1){
            System.out.println("read:"+read);
            
            buf1.flip();
            System.out.println("buf1:"+charset.decode(buf1));
            buf1.clear();
            
            buf2.flip();
            System.out.println("buf2:"+charset.decode(buf2));
            buf2.clear();
            
            read = channel.read(bufArray);
        }
        
        channel.close();
    }
    
    @Test
    public void testGather() throws IOException, URISyntaxException{
        ByteBuffer buf1 = ByteBuffer.allocate(48);
        ByteBuffer buf2 = ByteBuffer.allocate(48);
        
        buf1.put("abcde".getBytes());
        buf2.put("high".getBytes());
        
//        ByteBuffer buf1 = ByteBuffer.wrap("abcde".getBytes());
//        ByteBuffer buf2 = ByteBuffer.wrap("high".getBytes());
        
        RandomAccessFile file = new RandomAccessFile(new File(this.getClass().getResource("output.txt").toURI()), "rw");
        FileChannel channel = file.getChannel();
        //channel.position(channel.size());
        
        ByteBuffer[] bufArray = {buf1,buf2};
        buf1.flip();
        buf2.flip();
        channel.write(bufArray);
        
        channel.close();
    }
}
